import { useEffect, useState } from 'react'
import { getHerosList } from '@/api/hero'

function useAuth() {
    const isLogin = sessionStorage.getItem('token') ? true : false
    return {
        isLogin
    }
}


function usePageInfo() {
    const [pageInfo, setPageInfo] = useState({
        pagenum: 1,
        pagesize: 5
    })
    const [pagination, setPagination] = useState({
        total: 0,
        pageSize: 5,
        pageSizeOptions: [5, 8, 10, 15],
        showQuickJumper: true
    })
    const [data, setData] = useState([])

    const init = () => {
        getHerosList(pageInfo).then((res: any) => {
            const data = res.data
            data.forEach((item: any, index: number) => {
                data[index].key = item._id
            })
            setData(res.data)
            setPagination({
                ...pagination,
                total: res.total,
                pageSize: pageInfo.pagesize
            })
            // console.log(res)
        })
    }

    // 修改页数
    const change = (pageInfo: any) => {
        // pageInfo.current
        console.log(pageInfo)
        setPageInfo({
            pagenum: pageInfo.current,
            pagesize: pageInfo.pageSize
        })
    }

    // 搜索
    const search = (query: string) => {
        getHerosList({
            ...pageInfo,
            query
        }).then((res: any) => {
            const data = res.data
            data.forEach((item: any, index: number) => {
                data[index].key = item._id
            })
            setData(res.data)
        })
    }

    useEffect(() => {
        init()
    }, [pageInfo])

    return {
        data,
        pagination,
        change,
        search
    }
}

export {
    useAuth,
    usePageInfo
}